package com.etc.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.etc.entity.Orders;
import com.etc.entity.Showings;
import com.etc.filter.AlipayConfig;
import com.etc.service.OrdersService;
import com.etc.service.ShowingService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author luliang
 */
@Controller
@RequestMapping("/PayController")
public class PayController {
    Logger logger=Logger.getLogger(PayController.class);
    @Autowired
    ShowingService service;

    @Autowired
    OrdersService ordersService;

        @RequestMapping("/doPay")
        private void doPay(HttpServletRequest request2, HttpServletResponse response) {
        //Random r=new Random();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(AlipayConfig.return_url);
        request.setNotifyUrl(AlipayConfig.notify_url);

            String userName="尔康";
            String movieName=request2.getParameter("movieName");//电影名
            String count = request2.getParameter("count");
            /*logger.debug("从前台接收回来的数据:"+movieName+","+count);*/
            /*for (String s:seatList) {
                logger.debug("从前台接收回来的集合:"+s);
            }*/

            //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        /*String total_amount =Integer.toString(r.nextInt(9)+1);*/
        String total_amount =request2.getParameter("total");
        //订单名称，必填
        String subject ="购买["+movieName+"]的电影票"+count+"张";
        //商品描述，可空
        String body = "尊重的会员:"+userName+",感谢您购买["+movieName+"]的电影票"+count+"张,感谢您对本影院的支持";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset="+AlipayConfig.charset);
        try {
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("出问题了");
        }// 直接将完整的表单html输出到页面

    }

    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些rsaCheckV2,rsaCheckV1
        boolean signVerified = AlipaySignature.rsaCheckV2(params, AlipayConfig.alipay_public_key,
                AlipayConfig.charset, AlipayConfig.sign_type); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
            //payService.updateById(Integer.valueOf(out_trade_no))
            //return "ok";//以下是自己写的代码,和模板无关
            logger.debug("支付OK,完成");
            List<Orders> ordersList = ( List<Orders>)request.getSession().getAttribute("ordersList");
            for(Orders orders:ordersList){
                logger.debug("支付OK,完成"+orders);
                ordersService.updateOrderStatus(orders);
            }
            return "front/orderList";
        }else{
            //return "no";//跳转付款失败页面
            logger.debug("支付no,失败");
            return "success";
        }
    }

    /**
     * 获取到该电影厅的总座位数
     * @param showNo
     * @return
     */
    @RequestMapping("/getCountSeat")
    @ResponseBody
    public Showings getCountSeat(@RequestParam(value = "showNo")int showNo){
        Showings showSeat = service.getShowSeat(showNo);
        return showSeat;
    }

    /**
     * 获取到订单对象集合,从而获取到售出的座位号
     * @param showNo  上映序号
     * @return
     */
    @RequestMapping("/getOrders")
    @ResponseBody
    public List<Orders> getOrders(@RequestParam(value = "showNo")int showNo){
        List<Orders> list = service.getSellSeatByShowNo(showNo);
        return list;
    }

    @RequestMapping("/goMoviesJsp")
    public ModelAndView goMoviesJsp(int movieNo){
        ModelAndView mv = new ModelAndView();
        mv.addObject("go_movieNo",movieNo);
        mv.setViewName("front/movies");
        return mv;
    }

    @RequestMapping("/goTickets")
    public ModelAndView goTickets(int showsNo){
        ModelAndView mv = new ModelAndView();
        mv.addObject("showsNo",showsNo);
        mv.setViewName("front/tickets");
        return mv;
    }

    @RequestMapping("/getShowings")
    @ResponseBody
    public List<Showings> getShowings(@RequestParam(value = "mov_no") int mov_no,
                                    @RequestParam(value = "day",defaultValue = "0")int day){
        List<Showings> s = service.getShowingsByMovieAndDay(mov_no, day);
        return s;
    }

    @RequestMapping("/addOrder")
    @ResponseBody
    public boolean addOrder(@RequestParam(value="list") String list,HttpServletRequest request){
         boolean flag=true;
        List<Orders> ordersList = JSON.parseArray(list,Orders.class);
        request.getSession().setAttribute("ordersList",ordersList);
        for(Orders orders:ordersList){
            boolean b = ordersService.addOrder(orders);
            int i = service.doDelSeatByShwoingNo(orders.getShowing_no());
            if (b == false || i==0){
                flag= false;
            }
        }
        return flag;
    }

    @RequestMapping("/goListJsp")
    public ModelAndView goListJsp(@RequestParam(value = "movieName",defaultValue = "")String movieName){
        ModelAndView mv = new ModelAndView();
        mv.addObject("keyWord",movieName);
        mv.setViewName("front/list");
        return mv;
    }

}
